#!/usr/local/bin python3
# coding=utf-8

"""
钉钉定时群提醒机器人
author：duicym
date：2017-12-18 16:17:20

"""

import os
from urllib import parse, request
import json
import time

import django


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dingtalkBot.settings")
django.setup()

from modelBot.models import DingBots

# 推送机器人类
class DingBot(object):
    """ dingTalk机器人实例 """
    webHook = ''

    def __init__(self, web_hook):
        super(DingBot, self).__init__()
        self.webHook = web_hook

    # text类型
    def sentText(self, content, is_at_all=False, at_mobiles=[]):
        data = {"msgtype": "text", "text": {"content": content}, "at": {"atMobiles": at_mobiles, "isAtAll": is_at_all}}
        return self.post(data)

    # actionCard 类型
    def setActionCard(self, actionCard):
        data = actionCard.getData()
        return self.post(data)

    def post(self, data):
        post_data = json.dumps(data).encode(encoding='utf-8')
        print(post_data)
        req = request.Request(self.webHook, post_data)

        req.add_header('Content-Type', 'application/json')
        content = request.urlopen(req).read()
        return content


# ActionCard类
class ActionCard(object):
    """
    ActionCard 消息结构字段
    整体跳转 需要配置 singleTitle singleURL 不需要配置 btns
    独立跳转 需要配置 btns 不需要配置 singleTitle singleURL
    """
    title = ''
    text = ''
    hideAvatar = ''  # 0-正常发消息者头像,1-隐藏发消息者头像
    btnOrientation = ''  # 0-按钮竖直排列，1-按钮横向排列
    btns = []
    singleTitle = ''
    singleURL = ''

    def __init__(self, args=""):
        super(ActionCard, self).__init__()
        self.args = args

    def putBtn(self, title, actionURL):
        self.btns.append({"title": title, "actionURL": actionURL})

    def getData(self):
        data = {"actionCard": {"title": self.title, "text": self.text, "hideAvatar": self.hideAvatar,
                               "btnOrientation": self.btnOrientation, "btns": self.btns,
                               "singleTitle": self.singleTitle,
                               "singleURL": self.singleURL},
                "msgtype": "actionCard"}
        return data


if __name__ == "__main__":
    ac = ActionCard()
    ac.title = "下班打卡啦！"
    ac.text = "![screenshot](@lADPBY0V4tLH_-vNAtDNBQA) " \
              "ლ ( ◕  ᗜ  ◕ ) ლ亲们工作一天，辛苦啦！下班一定要记得打卡呦~"
    ac.singleTitle = "点我打卡"
    # 钉钉考勤的链接
    ac.singleURL = "dingtalk://dingtalkclient/action/switchtab?index=2&name=work&scene=1&corpid=&appid=158"
    ac.hideAvatar = "0"
    ac.btnOrientation = "0"
    webHooks = DingBots.objects.all()

    while True:
        if time.strftime("%H:%M", time.localtime()) in ['18:00', '21:00']:
            print('打卡啦！', time.asctime(time.localtime(time.time())))
            webHooks = DingBots.objects.all()
            for webhook in webHooks:
                bot = DingBot('https://oapi.dingtalk.com/robot/send?access_token='+webhook)
                bot.setActionCard(ac)
        time.sleep(60)
